package week01;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lv
 * @date 2021/3/20 8:01
 */
public class HelloClassLoader extends ClassLoader{

    public static void main(String[] args){
        try {
            Class clazz = new  HelloClassLoader().findClass("Hello");

            Object o = clazz.newInstance();
            Method hello = clazz.getDeclaredMethod("hello");
            hello.invoke(o);

        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected Class<?> findClass(String name){
        byte[] bytes= new byte[0];
        try {
            bytes = readBytes("D:\\java\\geekbang\\document\\week01\\Hello.xlass");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defineClass(name,bytes,0,bytes.length);
    }
    private static byte[] readBytes(String path) throws IOException {
        File file = new File(path);
        InputStream fis = new FileInputStream(file);
        List<Byte> list = new ArrayList<>();
        int n;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((n = fis.read()) != -1) {
            bos.write(255-n);
        }
        return  bos.toByteArray();
    }
}
